{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from collections import OrderedDict\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "import dendropy\n",
    "from dendropy.calculate import popgenstat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Genes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "genes_species = OrderedDict()\n",
    "my_species = ['RESTV', 'SUDV']\n",
    "my_genes = ['NP', 'L', 'VP35', 'VP40']\n",
    "\n",
    "\n",
    "for name in my_genes:\n",
    "    gene_name = name.split('.')[0]\n",
    "    char_mat = dendropy.DnaCharacterMatrix.get_from_path('%s_align.fasta' % name, 'fasta')\n",
    "    genes_species[gene_name] = {}\n",
    "    \n",
    "    for species in my_species:\n",
    "        genes_species[gene_name][species] = dendropy.DnaCharacterMatrix()\n",
    "    for taxon, char_map in char_mat.items():\n",
    "        species = taxon.label.split('_')[0]\n",
    "        if species in my_species:\n",
    "            genes_species[gene_name][species].taxon_namespace.add_taxon(taxon)\n",
    "            genes_species[gene_name][species][taxon] = char_map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>seg_sites (RESTV)</th>\n",
       "      <th>nuc_div (RESTV)</th>\n",
       "      <th>taj_d (RESTV)</th>\n",
       "      <th>wat_theta (RESTV)</th>\n",
       "      <th>seg_sites (SUDV)</th>\n",
       "      <th>nuc_div (SUDV)</th>\n",
       "      <th>taj_d (SUDV)</th>\n",
       "      <th>wat_theta (SUDV)</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>NP</th>\n",
       "      <td>113.0</td>\n",
       "      <td>0.020659</td>\n",
       "      <td>-0.482275</td>\n",
       "      <td>49.489051</td>\n",
       "      <td>118.0</td>\n",
       "      <td>0.029630</td>\n",
       "      <td>1.203522</td>\n",
       "      <td>56.64</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>L</th>\n",
       "      <td>288.0</td>\n",
       "      <td>0.018143</td>\n",
       "      <td>-0.295386</td>\n",
       "      <td>126.131387</td>\n",
       "      <td>282.0</td>\n",
       "      <td>0.024193</td>\n",
       "      <td>1.412350</td>\n",
       "      <td>135.36</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>VP35</th>\n",
       "      <td>43.0</td>\n",
       "      <td>0.017427</td>\n",
       "      <td>-0.553739</td>\n",
       "      <td>18.832117</td>\n",
       "      <td>50.0</td>\n",
       "      <td>0.027761</td>\n",
       "      <td>1.069061</td>\n",
       "      <td>24.00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>VP40</th>\n",
       "      <td>61.0</td>\n",
       "      <td>0.026155</td>\n",
       "      <td>-0.188135</td>\n",
       "      <td>26.715328</td>\n",
       "      <td>41.0</td>\n",
       "      <td>0.023517</td>\n",
       "      <td>1.269160</td>\n",
       "      <td>19.68</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      seg_sites (RESTV)  nuc_div (RESTV)  taj_d (RESTV)  wat_theta (RESTV)  \\\n",
       "NP                113.0         0.020659      -0.482275          49.489051   \n",
       "L                 288.0         0.018143      -0.295386         126.131387   \n",
       "VP35               43.0         0.017427      -0.553739          18.832117   \n",
       "VP40               61.0         0.026155      -0.188135          26.715328   \n",
       "\n",
       "      seg_sites (SUDV)  nuc_div (SUDV)  taj_d (SUDV)  wat_theta (SUDV)  \n",
       "NP               118.0        0.029630      1.203522             56.64  \n",
       "L                282.0        0.024193      1.412350            135.36  \n",
       "VP35              50.0        0.027761      1.069061             24.00  \n",
       "VP40              41.0        0.023517      1.269160             19.68  "
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "summary = np.ndarray(shape=(len(genes_species), 4 * len(my_species)))\n",
    "stats = ['seg_sites', 'nuc_div', 'taj_d', 'wat_theta']\n",
    "for row, (gene, species_data) in enumerate(genes_species.items()):\n",
    "    for col_base, species in enumerate(my_species):\n",
    "        summary[row, col_base * 4] = popgenstat.num_segregating_sites(species_data[species])\n",
    "        summary[row, col_base * 4 + 1] = popgenstat.nucleotide_diversity(species_data[species])\n",
    "        summary[row, col_base * 4 + 2] = popgenstat.tajimas_d(species_data[species])\n",
    "        summary[row, col_base * 4 + 3] = popgenstat.wattersons_theta(species_data[species])\n",
    "columns = []\n",
    "for species in my_species:\n",
    "    columns.extend(['%s (%s)' % (stat, species) for stat in stats])\n",
    "df = pd.DataFrame(summary, index=genes_species.keys(), columns=columns)\n",
    "df # vs print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Genomes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def do_basic_popgen(seqs):\n",
    "    num_seg_sites = popgenstat.num_segregating_sites(seqs)\n",
    "    avg_pair = popgenstat.average_number_of_pairwise_differences(seqs)\n",
    "    nuc_div = popgenstat.nucleotide_diversity(seqs)\n",
    "    print('Segregating sites: %d, Avg pairwise diffs: %.2f, Nucleotide diversity %.6f' % (num_seg_sites, avg_pair, nuc_div))\n",
    "    print(\"Watterson's theta: %s\" % popgenstat.wattersons_theta(seqs))\n",
    "    print(\"Tajima's D: %s\" % popgenstat.tajimas_d(seqs))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BDBV_KC545393\n",
      "BDBV_KC545395\n",
      "BDBV_KC545394\n",
      "BDBV_KC545396\n",
      "BDBV_FJ217161\n",
      "TAFV_FJ217162\n",
      "EBOV_2014_KM034549\n",
      "EBOV_2014_KM034550\n",
      "EBOV_2014_KM034554\n",
      "EBOV_2014_KM034555\n",
      "EBOV_2014_KM034556\n",
      "EBOV_2014_KM034557\n",
      "EBOV_2014_KM034560\n",
      "EBOV_2014_KM034551\n",
      "EBOV_2014_KM034552\n",
      "EBOV_2014_KM034553\n",
      "EBOV_2014_KM034558\n",
      "EBOV_2014_KM034559\n",
      "EBOV_2014_KM034561\n",
      "EBOV_2014_KM034562\n",
      "EBOV_2014_KM034563\n",
      "EBOV_1976_AF272001\n",
      "EBOV_1976_KC242801\n",
      "EBOV_1995_KC242796\n",
      "EBOV_1995_KC242799\n",
      "EBOV_2007_KC242784\n",
      "EBOV_2007_KC242785\n",
      "EBOV_2007_KC242787\n",
      "EBOV_2007_KC242786\n",
      "EBOV_2007_KC242789\n",
      "EBOV_2007_KC242788\n",
      "EBOV_2007_KC242790\n",
      "RESTV_AB050936\n",
      "RESTV_JX477166\n",
      "RESTV_FJ621585\n",
      "RESTV_JX477165\n",
      "RESTV_FJ621583\n",
      "RESTV_FJ621584\n",
      "SUDV_KC242783\n",
      "SUDV_FJ968794\n",
      "SUDV_EU338380\n",
      "SUDV_AY729654\n",
      "SUDV_JN638998\n",
      "SUDV_KC589025\n"
     ]
    }
   ],
   "source": [
    "#XXX change\n",
    "ebov_seqs = dendropy.DnaCharacterMatrix.get_from_path(\n",
    "    'trim.fasta', schema='fasta', data_type='dna')\n",
    "sl_2014 = []\n",
    "drc_2007 = []\n",
    "ebov2007_set = dendropy.DnaCharacterMatrix()\n",
    "ebov2014_set = dendropy.DnaCharacterMatrix()\n",
    "for taxon, char_map in ebov_seqs.items():\n",
    "    print(taxon.label)\n",
    "    if taxon.label.startswith('EBOV_2014') and len(sl_2014) < 8:\n",
    "        sl_2014.append(char_map)\n",
    "        ebov2014_set.taxon_namespace.add_taxon(taxon)\n",
    "        ebov2014_set[taxon] = char_map\n",
    "    elif taxon.label.startswith('EBOV_2007'):\n",
    "        drc_2007.append(char_map)\n",
    "        ebov2007_set.taxon_namespace.add_taxon(taxon)\n",
    "        ebov2007_set[taxon] = char_map\n",
    "        #ebov2007_set.extend_map({taxon: char_map})\n",
    "del ebov_seqs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2007 outbreak:\n",
      "Number of individuals: 7\n",
      "Segregating sites: 25, Avg pairwise diffs: 7.71, Nucleotide diversity 0.000412\n",
      "Watterson's theta: 10.204081632653063\n",
      "Tajima's D: -1.383114157484101\n",
      "\n",
      "2014 outbreak:\n",
      "Number of individuals: 8\n",
      "Segregating sites: 6, Avg pairwise diffs: 2.79, Nucleotide diversity 0.000149\n",
      "Watterson's theta: 2.31404958677686\n",
      "Tajima's D: 0.9501208027581887\n"
     ]
    }
   ],
   "source": [
    "print('2007 outbreak:')\n",
    "print('Number of individuals: %s' % len(ebov2007_set.taxon_namespace))\n",
    "do_basic_popgen(ebov2007_set)\n",
    "\n",
    "print('\\n2014 outbreak:')\n",
    "print('Number of individuals: %s' % len(ebov2014_set.taxon_namespace))\n",
    "do_basic_popgen(ebov2014_set)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n",
      "7\n"
     ]
    }
   ],
   "source": [
    "print(len(sl_2014))\n",
    "print(len(drc_2007))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "pair_stats = popgenstat.PopulationPairSummaryStatistics(sl_2014, drc_2007)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average number of pairwise differences irrespective of population: 284.46\n",
      "Average number of pairwise differences between populations: 535.82\n",
      "Average number of pairwise differences within populations: 10.50\n",
      "Average number of net pairwise differences : 525.32\n",
      "Number of segregating sites: 549\n",
      "Watterson's theta: 168.84\n",
      "Wakeley's Psi: 0.308\n",
      "Tajima's D: 3.05\n"
     ]
    }
   ],
   "source": [
    "print('Average number of pairwise differences irrespective of population: %.2f' %\n",
    "      pair_stats.average_number_of_pairwise_differences)\n",
    "print('Average number of pairwise differences between populations: %.2f' %\n",
    "      pair_stats.average_number_of_pairwise_differences_between)\n",
    "print('Average number of pairwise differences within populations: %.2f' %\n",
    "      pair_stats.average_number_of_pairwise_differences_within)\n",
    "print('Average number of net pairwise differences : %.2f' %\n",
    "      pair_stats.average_number_of_pairwise_differences_net)\n",
    "print('Number of segregating sites: %d' %\n",
    "      pair_stats.num_segregating_sites)\n",
    "print(\"Watterson's theta: %.2f\" %\n",
    "      pair_stats.wattersons_theta)\n",
    "print(\"Wakeley's Psi: %.3f\" % pair_stats.wakeleys_psi)\n",
    "print(\"Tajima's D: %.2f\" % pair_stats.tajimas_d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
